package top.zsyle.system.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zsyle.system.domain.Log;
import top.zsyle.system.mapper.LogMapper;
import top.zsyle.system.service.LogService;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.Date;

@Aspect
@Component
public class LogManager {

    @Autowired
    private LogMapper mapper;


    @Pointcut("@annotation(top.zsyle.system.aop.LogAop)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Log log = new Log();

        //拦截请求，进行下列操作（判断方法，ip，时间，注解内容）
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        //获取到注解到的方法
        Method method = methodSignature.getMethod();

        //获取logAop注解
        LogAop logAop = method.getAnnotation(LogAop.class);
        String name = logAop.name();
        Integer age = logAop.age();
        log.setLogaopName(name);
        log.setLogaopAge(age);

        String methodName = method.getName();
        log.setMethodName(methodName);

        InetAddress localHost = InetAddress.getLocalHost();
        String ip = localHost.getHostAddress();
        log.setIp(ip);

        log.setDate(new Date());
        mapper.add(log);

        //返回请求，执行下面的方法
        Object proceed = pjp.proceed();
        return proceed;
    }
}
